<?php

declare(strict_types=1);

namespace App\Api\Controller;

use App\Api\Middleware\ResponseMiddleware;
use App\Api\Request\UploadRequest;
use App\Exception\DefaultException;
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\Stringable\Str;
use Throwable;

#[Controller(prefix: 'api'), Middlewares([ResponseMiddleware::class])]
class UploadController
{
    /**
     * 上传文件
     * @param UploadRequest $request
     * @param FilesystemFactory $factory
     * @return array
     */
    #[PostMapping('upload')]
    public function store(UploadRequest $request, FilesystemFactory $factory): array
    {
        try {
            $file = $request->file('file');
            if ($request->validated() && $file->isValid()) {
                $path = sprintf('/user/%s/%s.%s', date('Ymd'), snowflake_id(), Str::lower($file->getExtension()));
                $factory->get('local')->writeStream($path, $file->getStream()->detach());
                return [
                    'url' => sprintf('%s/%s%s', config('file.storage.local.url'), config('file.storage.local.path'), $path),
                ];
            }
        } catch (Throwable $e) {}
        throw new DefaultException('文件上传失败');
    }
}
